<template>
	<div class="MainBody">
		<!-- <el-input v-model="input" placeholder="请输入内容"></el-input> -->
		<div class="leftBody">
			<h1>助农资讯</h1>
			<ul v-for="(item,index) in ZnMessDate" :key="index" v-if="index < 10">
				<li @click="skipMessInfo(item.znMessId)">{{item.messTitle}}</li>
			</ul>
		</div>
		<div class="centreBody">
			<PostComp :PostsData="PostsData">
			</PostComp>
			<div class="footer_page">
				<el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize"
					layout="total, prev, pager, next, jumper" :total="total"></el-pagination>
			</div>
		</div>
		<div class="rightBody">
			<el-button type="primary" icon="el-icon-edit" @click="creationEditor">发布 </el-button>
		</div>
		<el-dialog title="发布帖子" :visible.sync="dialogVisible" width="60%" :before-close="handleClose" center>
			<el-form :model="form" :rules="rules" ref="form" v-if="cleardata">
				<el-form-item label="帖子标题" :label-width="formLabelWidth" prop="postName">
					<el-input v-model="form.postName" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="帖子封面" :label-width="formLabelWidth" prop="contentCover">
					<el-upload class="orders-img_el_upload" show-file-list :action="upurl" :limit="limitCountImg" list-type="picture-card"
						:on-change="handleChange" :on-preview="handlePreview" :on-remove="handleRemove"
						:on-success="handleSuccess" :on-error="handleError" :file-list="fileList" 
						:class="{ disUoloadSty: noneBtnImg }" ref="upload" :disabled="uploadDisabled"
						@click.stop="submitUpload">
						<span class="orders-img_el_upload_btn">添加图片(最多三张)</span>
					</el-upload>
				</el-form-item>
				<el-form-item label="帖子内容" :label-width="formLabelWidth" prop="postContent">
					<div ref="editor"></div>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="cleardata">取 消</el-button>
				<el-button type="primary" @click="submitForm('form')">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import postsApi from "@/api/posts.js"
	import PostComp from "@/components/foreground/PostComponents.vue"
	import znMessApi from "@/api/znMessage.js"
	import Editor from "wangeditor"
	export default {
		components: {
			PostComp
		},
		data() {
			return {
				editor: null,
				input:"",
				total: 0,
				pageSize: 10,
				currentPage: 1,
				PostsData: [],
				ZnMessDate: [],
				dialogVisible: false,
				uploadDisabled: false,
				noneBtnImg: false,
				limitCountImg: 3,
				upurl: "/api/file/uploadList/posts",
				fileList: [],
				form: {
					postName: "",
					postContent: "",
					contentCover: ""
				},
				rules: {
					postName: [{
						required: true,
						message: "请输入帖子标题",
						trigger: 'blur'
					}]
				},
				formLabelWidth: '120px'
			}
		},
		mounted(){
			
			
		},
		methods: {
			skipMessInfo(item) {
				this.$router.push({
					path: `/ZnMessDetail/${item}`
				}).catch(err => err);
			},
			async SearchPostsAll() {
				if (this.$store.getters.gettoken == null) {
					const res = await postsApi.PostsAll("/znExchangePost/postsAll", {
						currentPage: this.currentPage,
						pageSize: this.pageSize
					});
					if (res.code == 200) {
						this.PostsData = res.data.records;
						this.total = res.data.total;
					}
				} else {
					const res = await postsApi.PostsAll("/znExchangePost/LogUserPostAll", {
						currentPage: this.currentPage,
						pageSize: this.pageSize
					});
					if (res.code == 200) {
						this.PostsData = res.data.records;
						this.total = res.data.total;
					}
				}

			},
			handleCurrentChange(page) {
				this.currentPage = page;
				this.SearchPostsAll();
			},
			async getZnMessageAll() {
				const res = await znMessApi.getZnMessageAll("/znMessage/getZnMessageAll");
				if (res.code == 200) {
					this.ZnMessDate = res.data
				}
			},
			handleClose(done) {
				this.$confirm('确认关闭？')
					.then(_ => {
						this.editor.destroy();
						this.editor = null;
						this.input = '';
						done();
					})
					.catch(_ => {});
			},
			creationEditor() {
				if(this.$store.getters.gettoken == null){
					this.$message.warning('您还未登录！');
				}else{
					this.dialogVisible = true;
					this.$nextTick(() => {
						this.editor = new Editor(this.$refs.editor)
						this.editor.config.uploadImgServer = "api/file/editUpload/posts"
						this.editor.config.uploadFileName = "file"
						this.editor.config.uploadVideoServer = 'api/file/editUpload/posts'
						this.editor.config.uploadVideoName = "file"
						this.editor.create()
					})
				}
			},
			cleardata() {
				this.dialogVisible = false;
				this.editor.destroy();
				this.editor = null;
				this.input = '';
			},
			async addPost() {
				let content = this.editor.txt.html();
				console.log(content);
				const res = await postsApi.addPost("/znExchangePost/addPost", {
					postName: this.form.postName,
					postContent: this.form.postContent = content,
					contentCover: this.form.contentCover
				});
				if (res.code == 200) {
					this.dialogFormVisible = false;
					this.$message.success(res.msg);
					this.SearchPostsAll();
				} else {
					this.$message.error(res.msg);
				}
			},
			handleError(err) {
				console.error("上传错误:", err);
				this.$message.error("上传失败，请重试！");
			},
			handleSuccess(response, file, fileList) {
				if (response.flag === true) {
					this.fileList = fileList;
					// 改为将所有文件名保存到数组中
					this.form.contentCover = fileList.map(file => file.response.data).join(",");
					if (fileList.length > 3) {
						this.uploadDisabled = true;
					}
					this.$message.success(response.message);
				} else {
					this.$message.error(response.message);
				}
			},
			handleChange(file, fileList) {
				this.noneBtnImg = fileList.length >= this.limitCountImg;
			},
			handleRemove(file, fileList) {
				this.noneBtnImg = fileList.length >= this.limitCountImg;
				this.fileList.pop();
				this.uploadDisabled = false;
			},
			handlePreview(file) {
				this.dialogImageUrl = file.url;
				this.dialogVisible = true;
			},
			submitUpload() {
				this.$refs.upload.submit();
			},
			submitForm(form) {
				this.$refs[form].validate((valid) => {
					if (valid) {
						this.addPost();
						this.$refs.form.resetFields();
						this.editor.destroy();
						this.editor = null;
					} else {
						return false;
					}
				});
			},
		},
		created() {
			this.SearchPostsAll();
			this.getZnMessageAll();
		}
	}
</script>

<style lang="scss" scoped>
	.MainBody {
		margin: 0 15% 3% 15%;
		display: flex;

		.leftBody {
			margin: 10px 20px 0 0;
			width: 18%;
			height: 86.5vh;
			background-color: #e7e7e7;
			border-radius: 4px;
			
			h1 {
				margin: 30px 0 50px 10px;
				line-height: 0;
				font-size: 20px;
				color: #2c92f8;
			}

			ul {
				overflow: hidden;
				margin-left: 10px;
				list-style: none;
				/* 去除默认点样式 */
				padding-left: 0;
				font-size: 16px;
				li {
					cursor: pointer;
					white-space: nowrap;
					text-overflow: ellipsis;
					overflow: hidden;
					margin-bottom: 30px;
				}
			}
		}

		.centreBody {
			width: 70%;
			.footer_page {
				height: 10%;
				position: relative;
				.el-pagination {
					position: absolute;
					right: 35%;
					bottom: 50%;
					transform: translateY(-90%);

				}
			}
		}

		.rightBody {
			width: 10%;
			margin: 10px 0 0 10px;
			position: fixed; 
			top: 100px; 
			right: 240px;
		}
	}
</style>